package com.xiaodou.mjf.web.xface.basic.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xiaodou.mjf.application.basic.service.SmsService;
import com.xiaodou.mjf.application.user.service.MemberSecurityService;
import com.xiaodou.mjf.entity.basic.Sms;
import com.xiaodou.mjf.entity.user.MemberSecurity;
import com.xiaodou.mjf.infrastructure.common.controller.ApiController;
import com.xiaodou.mjf.infrastructure.common.sms.SMSClient;
import com.xiaodou.mjf.infrastructure.common.utils.CodeGenerator;
import com.xiaodou.mjf.infrastructure.common.utils.DateUtils;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;
import com.xiaodou.mjf.web.xface.common.ResultCode;

/**
 * Created by Rocky on 2/26/15.
 */
@RestController
@RequestMapping("v1/basic")
public class VerifyCodeController extends ApiController {

	@Resource
	SmsService smsService;
	
	@Resource
	MemberSecurityService memberSecurityService;

	@RequestMapping("verify_code")
	public Map<String, Object> send(String phone, Integer type,HttpServletResponse response) {
		// 测试用 手机号 phone  短信验证码类型 type
		Sms entity ;
		if (StringUtils.isBlank(phone) || type == null) {
			return failure(ResultCode.MISSING_PARAMS);
		}
		//判断客户是否存在,不存在返回，不发验证码 add by David 2015/04/15 start
        if(Sms.RESET_LOGINPASSWORD.equals(type)){
        	MemberSecurity memberSecurity= memberSecurityService.getMember(phone);
        	if(memberSecurity==null){
        		return failure(ResultCode.USER_UNREGISTER);
        	}        	
        }
        // add by David 2015/04/15 end
		//查找sms表中 status为0的电话记录
		entity= smsService.findByPhone(phone,type);		
		if(entity!= null){
        	try {
        		//将上条电话记录状态置1;
        		entity.setStatus(Sms.DELETE);
        		smsService.save(entity);
    		} catch (Exception e) {
    			logger.error(e.toString());
    			return failure(ResultCode.SMS_UPDATE_ERROR);
    		}
        }
        
        entity = new Sms();
        String code= CodeGenerator.generateCode();
		// 验证码
        entity.setCode(code);
		// 手机号
        entity.setMobile(phone);
		// 验证类型
        entity.setType(type);
		// 过期时间
        entity.setExpiryTime(DateUtils.addMinutes(DateUtils.getCurrentTime(),Sms.EXPIRY_TIME));
        //将当前记录设置为正常
        entity.setStatus(Sms.NORMAL);

        response.setHeader("Access-Control-Allow-Origin","*");

		try {
			smsService.save(entity);
			SMSClient.sendValidateCode(code, phone);
		} catch (Exception e) {
			logger.error(e.toString());
			return failure(ResultCode.SMS_UPDATE_ERROR);
		}

		return success();

	}

}
